package com.hxm.coordinator;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.design.widget.CoordinatorLayout;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by hxm on 2017/6/24.
 * 描述：练习一
 */
public class FirstBehavior extends CoordinatorLayout.Behavior {

    private int dependsId;

    public FirstBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.BehaviorStyle);
        dependsId = typedArray.getResourceId(R.styleable.BehaviorStyle_dependsId, -1);
        typedArray.recycle();
    }

    //确定依赖关系
    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, View child, final View dependency) {
        dependency.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                float lastY = 0;
                float lastX = 0;
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        lastX = view.getX();
                        lastY = view.getY();
                        return false;
                    case MotionEvent.ACTION_UP:

                        break;
                    case MotionEvent.ACTION_MOVE:
                        float tx = view.getX() - lastX;
                        float ty = view.getY() - lastY;
                        dependency.setY(motionEvent.getY());
                        dependency.setX(motionEvent.getX());
                        break;
                }
                return false;
            }
        });
        return dependency.getId() == dependsId;
    }

    //当依赖的view发生变动时执行
    @Override
    public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {
        child.setY(dependency.getHeight() + dependency.getY());
        return true;
    }
}
